package com.nowcoder.community.config;

import com.nowcoder.community.utils.CommonUtil;
import com.nowcoder.community.utils.ConstantUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: shuhuang
 * @description:
 * @Date: 2023/1/28 10:46
 * @Version java version 1.8
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/static/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权
        http.authorizeRequests()
                .antMatchers("/user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow")
                .hasAnyAuthority(ConstantUtil.AUTHORITY_USER,
                        ConstantUtil.AUTHORITY_ADMIN,
                        ConstantUtil.AUTHORITY_MODERATOR)
                .antMatchers("/discuss/top",
                        "/discuss/wonderful")
                .hasAnyAuthority(ConstantUtil.AUTHORITY_MODERATOR)
                .antMatchers("/discuss/delete",
                        "/data/**")
                .hasAnyAuthority(ConstantUtil.AUTHORITY_ADMIN)
                .anyRequest().permitAll()
                //关闭CSRF验证,and()相当于就是XML标签的结束符，表示结束当前标签，然后开启新的配置
                //and方法表示结束当前标签，上下文回到HttpSecurity，开启新一轮的配置
                .and().csrf().disable();
        //权限处理
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    //没有登录时
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        String requestHeader = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(requestHeader)) {
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommonUtil.getJSONString(403, "你还没有登录！"));
                        } else {
                            response.sendRedirect(request.getContextPath() + "/login");
                        }

                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    //权限不足时
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        String requestHeader = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equals(requestHeader)) {
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommonUtil.getJSONString(403, "你没有访问此功能的权限！"));
                        } else {
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });

        //Secutiry底层会默认拦截/logout请求，进行退出处理
        //覆盖他默认的逻辑，才能执行我们自己的推出代码
        http.logout().logoutUrl("/securitylogout");
    }
}
